package com.logica.mdm.webservices.util;

import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

/**
 * Utility class to manipulate Strings.
 */
public final class MdmStringUtils {

	/** Input Accentued Chars. */
	public final static String INPUT_STRING = new String("àäéèêëîïôöùü");
	
	/** Corresponding output non accentued Chars. */
	public final static String OUTPUT_STRING = "aaeeeeiioouu";
	
	public final static Pattern patternSigeoId = Pattern.compile("^[a-zA-z]+(\\d+)$");
	
	/**
	 * Convert an input string to a lower cased String unaccentued
	 * @param inputString the input String 
	 * @return the result String, <code>null</code> if the inputString is empty or null
	 */
	public static String toLowerWithoutAccent(String inputString) {
		String result = inputString;
		if (!StringUtils.isEmpty(inputString)) {
			result = result.toLowerCase(Locale.FRENCH);

			result = StringUtils.replaceChars(result, INPUT_STRING, OUTPUT_STRING);
		}
		return result;
	}
	
	/**
	 * Create a request string from a field name including a toLower clause
	 * and a Translate clause to replace the accentued chars with the unaccentuedOnes.
	 * @param fieldName the fieldNameToSearch;
	 * @return the corresponding request, <code>null</code> if the fieldName is empty or null
	 */
	public static String getLowerWithoutAccentQuery(String fieldName) {
		String result = null;
		if (!StringUtils.isEmpty(fieldName)) {
			StringBuilder sb = new StringBuilder(80);
			sb.append("TRANSLATE(LOWER(");
			sb.append(fieldName);
			sb.append("), '");
			sb.append(INPUT_STRING);
			sb.append("', '");
			sb.append(OUTPUT_STRING);
			sb.append("')");
			result = sb.toString();
		}
		return result;
	}
	/**
	 * Remove the alpha part of the Sigeo ID.
	 * @param sigeoIdStr 
	 * 		The sigeoId
	 * @return String
	 * 		The new sigeoId without alpha 
	 */
	public static String filterAlphaSigeoID(String sigeoIdStr){
		Matcher matcher = patternSigeoId.matcher(sigeoIdStr);
		if(matcher.find()){
			return matcher.group(1);
		}
		return null;
	}
}
